﻿
var geoc, canvas, backCanvas, pctx, mist, specialMarker, objs = [], ready = false, inputs = [];

$(window).resize(function () {
    if (ready) {
        canvas.height = $(window).height();
        canvas.width = $(window).width();
        backCanvas.height = $(window).height();
        backCanvas.width = $(window).width();

        paint();
    }
});

$(document).bind("pageinit", function () {
    //InputHandlers.Gps.useSampleData = true;
    //InputHandlers.Gps.timerInterval = 10000;

    if (InputHandlers.Gps.isAvailable()) {
        InputHandlers.Gps.enable(function (geo) {
            geoc = geo;
            getLocations(geoc.latitude, geoc.longitude);
            init();
        });
    }
    else {
        geoc = GeoCoordinates.newInstance(39.955959, -86.013181);
        init();
        getLocations(39.955959, -86.013181);
    }
});

function init() {
    ready = true;

    inputs.push(InputHandlers.Gps);
    inputs.push(InputHandlers.Compass);
    inputs.push(InputHandlers.Tap);
    inputs.push(InputHandlers.Keyboard);

    canvas = document.createElement('canvas');
    canvas.top = 0;
    canvas.left = 0;
    canvas.height = $(window).height();
    canvas.width = $(window).width();
    canvas.style.position = "absolute";
    canvas.style.zIndex = 1;

    backCanvas = document.createElement('canvas');
    backCanvas.top = 0;
    backCanvas.left = 0;
    backCanvas.height = $(window).height();
    backCanvas.width = $(window).width();
    backCanvas.style.position = "absolute";
    backCanvas.style.zIndex = 0;

    document.getElementsByTagName('article')[0].appendChild(backCanvas);
    document.getElementsByTagName('article')[0].appendChild(canvas);

    pctx = PaintingContext.newInstance();
    pctx.backLayer = backCanvas.getContext("2d");
    pctx.frontLayer = canvas.getContext("2d");
    pctx.viewPort = ViewPort.newInstance(6, util._90, util._45);
    pctx.camera = Placement.newInstance(); //new Camera();
    pctx.camera.w = 3.0;
    pctx.camera.h = 6.25;
    pctx.camera.setBearing(util._90);
    if (geoc != null) {
        pctx.camera.x = geoc.x;
        pctx.camera.y = geoc.y;
        geoc.updateLocation(pctx);
    }
    else {
        pctx.camera.x = 30.0;
        pctx.camera.y = 10.0;
    }

    /*Mist*/
    objs.push(MistObject.newInstance(1000, 0.2));


    /*Clouds*/
    for (var i = 0; i < 25; i++) {
        var cloud = CloudObject.newInstance();
        cloud.h = util.random(50, 300);
        cloud.w = cloud.h * 2;
        cloud.x = util.random(pctx.camera.x - 1800, pctx.camera.x + 1800);
        cloud.y = util.random(pctx.camera.y - 1800, pctx.camera.y + 1800);
        cloud.z = util.random(400, 600);
        cloud.speed = Math.random() * .04;
        objs.push(cloud);
    }

    /*Marker*/
    var sf = InputHandlers.Gps.sampleFeed;
    for (var j = 0; j < sf.length; j++) {
        var tg = GeoCoordinates.newInstance(sf[j].lat, sf[j].lon);
        var clr = ["blue", "red", "green", "pink", "orange", "yellow"]
        specialMarker = MapMarkerObject.newInstance("Point " + (j + 1), clr[(j % clr.length)]);
        specialMarker.w = 50;
        specialMarker.h = 300;
        specialMarker.z = 0;
        specialMarker.x = tg.x;
        specialMarker.y = tg.y;
        specialMarker.textColor = "black";
        specialMarker.setBearing(util._180);
        specialMarker.update();
        objs.push(specialMarker);
    }

    /*Trees*/
    for (var j = 0; j < 500; j++) {

        var s = util.random(15, 70);
        var tree = TreeObject.newInstance();
        tree.w = s;
        tree.h = s;
        tree.z = 0;
        tree.x = util.random(pctx.camera.x - 3600, pctx.camera.x + 3600);
        tree.y = util.random(pctx.camera.y - 3600, pctx.camera.y + 3600);
        tree.setBearing(util.radians(util.random(180)));
        tree.update();
        objs.push(tree);
    }

    /*Birds*/
    for (var j = 0; j < 30; j++) {
        var bird = FlyingBirdObject.newInstance();
        bird.bearing = util.radians(util.random(0, 359));
        bird.h = util.random(2, 4);
        bird.w = bird.h;
        bird.x = util.random(pctx.camera.x - 500, pctx.camera.x + 500);
        bird.y = util.random(pctx.camera.y - 500, pctx.camera.y + 500);
        bird.color = "rgb(" + util.random(0, 255) + ", " + util.random(0, 255) + ", " + util.random(0, 255) + ")";
        bird.update();
        objs.push(bird);
    }
    // Other sprites
    for (var j = 0; j < 30; j++) {
        var dude = TestDudeObject.newInstance((j % 3) == 1 ? AdvancedSprites.Hero : ((j % 3) == 2 ? AdvancedSprites.Marine : AdvancedSprites.Spencer));
        dude.bearing = util.radians(util.random(0, 359));
        dude.h = 6;
        dude.w = 4;
        dude.x = util.random(pctx.camera.x - 200, pctx.camera.x + 200);
        dude.y = util.random(pctx.camera.y - 200, pctx.camera.y + 200);
        dude.color = "rgb(" + util.random(0, 255) + ", " + util.random(0, 255) + ", " + util.random(0, 255) + ")";
        dude.update();
        objs.push(dude);
    }

    for (var k = 0; k < inputs.length; k++) {
        if (inputs[k].isAvailable()) {
            inputs[k].enable();
        }
    }

    setInterval(paint, 100);
}

function paint() {
    for (var k = 0; k < inputs.length; k++) {
        if (inputs[k].enabled) {
            inputs[k].update(pctx);
        }
    }

    pctx.frontLayer.clearRect(0, 0, canvas.width, canvas.height);

    pctx.viewPort.setPixelSize(canvas.width, canvas.height);
    pctx.gameObject = null;

    // Background Painters
    Painters.Sky2.paint(pctx);
    Painters.Ground.paint(pctx);

    // Update Locations of Object Painters
    /*if (InputHandlers.Gps.geo != null) {
		specialMarker.x = InputHandlers.Gps.geo.x;
		specialMarker.y = InputHandlers.Gps.geo.y;
	}*/
    for (var i = 0; i < objs.length; i++) objs[i].updateLocation(pctx);

    // Order painters by distance
    util.orderByDistance(objs);

    // Paint away!
    for (var i = 0; i < objs.length; i++) {
        var o = objs[i];
        o.tick();
        if (o.locationRelativeToCamera != null && o.locationRelativeToCamera.visible) {
            pctx.gameObject = o;
            o.getPainter().paint(pctx);
        }
    }

    txt = ("CAMERA - Bearing: " + pctx.camera.getBearingDegrees() + ", Line Of Sight: " + pctx.camera.getLineOfSightDegrees());
    var yy = 10;
    pctx.frontLayer.fillStyle = "#00A";
    pctx.frontLayer.fillText(txt, 10, yy);

    if (InputHandlers.Gps.enabled && InputHandlers.Gps != null && InputHandlers.Gps.geo != null) {
        var gps = InputHandlers.Gps;
        var txt = ("Latitude: " + gps.geo.latitude + ", Longitude: " + gps.geo.longitude +
			", TimeSinceUpdate: " + gps.timeSinceLastUpdate);

        yy += 10;
        pctx.frontLayer.fillStyle = "#000";
        pctx.frontLayer.fillText(txt, 10, yy);

        txt = ("X: " + gps.geo.x + ", Y: " + gps.geo.y + ", Relative Angle: " + util.degrees(gps.geo.locationRelativeToCamera.placement.angleFromCamera) +
			", Distance: " + gps.geo.locationRelativeToCamera.distance);

        yy += 10;
        pctx.frontLayer.fillStyle = "#000";
        pctx.frontLayer.fillText(txt, 10, yy);
    }
    if (InputHandlers.Compass.enabled) {
        txt = ("Compass Bearing: " + InputHandlers.Compass.getBearingDegrees() + ", TimeSinceUpdate: " + InputHandlers.Compass.timeSinceLastUpdate);

        yy += 10;
        pctx.frontLayer.fillStyle = "#A00";
        pctx.frontLayer.fillText(txt, 10, yy);
    }
}

function getLocations(lat, long, radius) {
    if (radius == null) radius = 3500;

    var pyrmont = new google.maps.LatLng(lat, long),

		map = new google.maps.Map(document.getElementById('map'), {
		    mapTypeId: google.maps.MapTypeId.ROADMAP,
		    center: pyrmont,
		    zoom: 15
		}),
		request = {
		    location: pyrmont,
		    "radius": radius
		},
		infowindow = new google.maps.InfoWindow();

    var service = new google.maps.places.PlacesService(map);
    service.search(request, function (results, status) {
        if (status == google.maps.places.PlacesServiceStatus.OK) {
            for (var i = 0; i < results.length; i++) {
                var loc = util.toECEF(results[i].geometry.location.Xa, results[i].geometry.location.Ya);
                var s = 50;
                var place = MapMarkerObject.newInstance(results[i].name, "red");
                place.textColor = "black";
                place.w = s;
                place.h = s * 2;
                place.x = loc[0];
                place.y = loc[1];
                place.z = 0;
                place.setBearing(0);
                place.update();
                objs.push(place);
            }
        }
    });
}